package com.jeecg.jing.controller;
import com.jeecg.jing.entity.*;
import com.jeecg.jing.entity.excel.*;
import com.jeecg.jing.service.ZTakeinServiceI;

import java.io.InputStream;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.criterion.*;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.jeecgframework.core.util.ExceptionUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Title: Controller
 * @Description: 客户信息
 * @author onlineGenerator
 * @date 2018-11-01 09:53:32
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/zTakeinController")
public class ZTakeinController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(ZTakeinController.class);

	@Autowired
	private ZTakeinServiceI zTakeinService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ControllerUtil controllerUtil;

	/**
	 * 客户信息列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return controllerUtil.list(request);
	}

	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ZTakeinEntity zTakein,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		controllerUtil.datagrid(zTakein, request, response, dataGrid);
	}

	/**
	 * 删除客户信息
	 *
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ZTakeinEntity zTakein, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		zTakein = systemService.getEntity(ZTakeinEntity.class, zTakein.getId());
		message = "客户信息删除成功";
		try{
			zTakeinService.delete(zTakein);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "客户信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除客户信息
	 *
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "客户信息删除成功";
		try{
			for(String id:ids.split(",")){
				ZTakeinEntity zTakein = systemService.getEntity(ZTakeinEntity.class,
				id
				);
				zTakeinService.delete(zTakein);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "客户信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加客户信息
	 *
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZTakeinEntity zTakein, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "客户信息添加成功";
		try{
			zTakeinService.save(zTakein);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "客户信息添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新客户信息
	 *
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZTakeinEntity zTakein, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "客户信息更新成功";
		if("2".equals(zTakein.getStatus())) {
			zTakein.setOutTime(new Date());
		}
		ZTakeinEntity t = zTakeinService.get(ZTakeinEntity.class, zTakein.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(zTakein, t);
			zTakeinService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "客户信息更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 客户信息新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZTakeinEntity zTakein, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zTakein.getId())) {
			zTakein = zTakeinService.getEntity(ZTakeinEntity.class, zTakein.getId());
			req.setAttribute("zTakein", zTakein);
		}
		return new ModelAndView("com/jeecg/jing/zTakein-add");
	}
	/**
	 * 客户信息编辑页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZTakeinEntity zTakein, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zTakein.getId())) {
			zTakein = zTakeinService.getEntity(ZTakeinEntity.class, zTakein.getId());
			req.setAttribute("zTakein", zTakein);
		}
		ModelAndView mv = new ModelAndView("com/jeecg/jing/zTakein-update");
		mv.addObject("key", req.getParameter("key"));
		return mv;
	}

	@RequestMapping(params = "goPrint")
	public ModelAndView goPrint(ZTakeinEntity zTakein, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zTakein.getId())) {
			zTakein = zTakeinService.getEntity(ZTakeinEntity.class, zTakein.getId());
			req.setAttribute("zTakein", zTakein);
		}
		ModelAndView mv = new ModelAndView("com/jeecg/jing/zTakein-print");
		mv.addObject("now", new Date());
		mv.addObject("pname", req.getParameter("pname"));
		return mv;
	}

	/**
	 * 导入功能跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","zTakeinController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	@RequestMapping(params = "upload_out")
	public ModelAndView upload_out(HttpServletRequest req) {
		req.setAttribute("controller_name","zTakeinController");
		req.setAttribute("method_name","importExcel_out");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(ZTakeinEntity zTakein,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) throws Exception {
		return controllerUtil.exportXls(zTakein, request, dataGrid, modelMap);
	}

	/**
	 * 导出excel 使模板
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ZTakeinEntity zTakein,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"客户信息");
    	modelMap.put(NormalExcelConstants.CLASS,ZTakeinEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("客户信息列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@RequestMapping(params = "importExcel_out", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel_out(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZTakeinEntity> listZTakeinEntitys = import_new_out(file.getInputStream(),ZTakeinEntity.class,params);
				zTakeinService.save(listZTakeinEntitys);
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！"+e.getMessage());
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZTakeinEntity> listZTakeinEntitys = import_new(file.getInputStream(),ZTakeinEntity.class,params);
				zTakeinService.save(listZTakeinEntitys);
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！"+e.getMessage());
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	private List<ZTakeinEntity> import_new(InputStream inputstream, Class<ZTakeinEntity> zTakeinEntityClass, ImportParams params) throws Exception {
		Workbook book = null;
		boolean isXSSFWorkbook = true;
		if (!(inputstream.markSupported())) {
			inputstream = new PushbackInputStream(inputstream, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(inputstream)) {
			book = new HSSFWorkbook(inputstream);
			isXSSFWorkbook = false;
		} else if (POIXMLDocument.hasOOXMLHeader(inputstream)) {
			book = new XSSFWorkbook(OPCPackage.open(inputstream));
		}
//		createErrorCellStyle(book);
		Sheet sheet = book.getSheetAt(0);
		Iterator<Row> rows = sheet.rowIterator();
		Row row = null;
		List<ZTakeinEntity> list = new ArrayList<ZTakeinEntity>();
		int i = 0;
		while (rows.hasNext()) {
			i++;
			row = rows.next();
			ZTakeinEntity item = new ZTakeinEntity();
			// 合同编号	收据编号	销售姓名	姓名				入金时间	金额、万	期限、月	利率	电话	汇款账户	到期时间	备注	到期日
			item.setContract(getString(row.getCell(0)));
			item.setReceipt(getString(row.getCell(1)));
			item.setSaleName(getString(row.getCell(2)));
			item.setCustomName(getString(row.getCell(3)));
			if(StringUtil.isEmpty(item.getCustomName()) || item.getCustomName().contains("姓名")) {
				continue;
			}
			item.setIdCard(getString(row.getCell(4)));
			try {
				item.setTakeinTime(row.getCell(5).getDateCellValue());
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(i + item.getCustomName()+"入金时间格式错误");
			}
			if(row.getCell(6) != null && row.getCell(6).getCellType() != Cell.CELL_TYPE_BLANK) {
				item.setAmount(new BigDecimal(getString(row.getCell(6))));
			}
			if(row.getCell(7) != null && row.getCell(7).getCellType() != Cell.CELL_TYPE_BLANK) {
				String limit = getString(row.getCell(7));
				if(!limit.contains("活期")) {
					item.setTimeLimit(limit.replace("个月", ""));
				}
			}
			if(row.getCell(8) != null && row.getCell(8).getCellType() != Cell.CELL_TYPE_BLANK) {
				item.setRate(new BigDecimal(getString(row.getCell(8))));
			}
			item.setPhone(getString(row.getCell(9)));
			item.setBankAccount(getString(row.getCell(10)));
			try {
				if(row.getCell(11).getCellType() != Cell.CELL_TYPE_STRING) {
					item.setEndTime(row.getCell(11).getDateCellValue());
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(i + item.getCustomName()+"到期时间格式错误");
			}
			item.setComment(getString(row.getCell(12)));
			item.setStatus("1");
			list.add(item);
		}
		return list;
	}

	private List<ZTakeinEntity> import_new_out(InputStream inputstream, Class<ZTakeinEntity> zTakeinEntityClass, ImportParams params) throws Exception {
		Workbook book = null;
		boolean isXSSFWorkbook = true;
		if (!(inputstream.markSupported())) {
			inputstream = new PushbackInputStream(inputstream, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(inputstream)) {
			book = new HSSFWorkbook(inputstream);
			isXSSFWorkbook = false;
		} else if (POIXMLDocument.hasOOXMLHeader(inputstream)) {
			book = new XSSFWorkbook(OPCPackage.open(inputstream));
		}
//		createErrorCellStyle(book);
		Sheet sheet = book.getSheetAt(0);
		Iterator<Row> rows = sheet.rowIterator();
		Row row = null;
		List<ZTakeinEntity> list = new ArrayList<ZTakeinEntity>();
		int i = 0;
		while (rows.hasNext()) {
			i++;
			row = rows.next();
			ZTakeinEntity item = new ZTakeinEntity();
			// 销售姓名	客户量	序号	姓名	身份证号	汇款账户	电话	备注	金额	利率	投资时间
			item.setSaleName(getString(row.getCell(0)));
			item.setCustomName(getString(row.getCell(3)));
			if(StringUtil.isEmpty(item.getCustomName()) || item.getCustomName().contains("姓名")) {
				continue;
			}
			item.setIdCard(getString(row.getCell(4)));
			item.setBankAccount(getString(row.getCell(5)));
			item.setPhone(getString(row.getCell(6)));
			item.setComment(getString(row.getCell(7)));
			if(row.getCell(8) != null && row.getCell(8).getCellType() != Cell.CELL_TYPE_BLANK) {
				item.setAmount(new BigDecimal(getString(row.getCell(8))));
			}
			if(row.getCell(9) != null && row.getCell(9).getCellType() != Cell.CELL_TYPE_BLANK) {
				item.setRate(new BigDecimal(getString(row.getCell(9))));
			}
			try {
				item.setInvestTime(row.getCell(10).getDateCellValue());
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(item.getCustomName()+"投资时间格式错误");
			}
			item.setStatus("2");
			list.add(item);
		}
		return list;
	}

	private String getString(Cell cell) {
		if(cell == null)
			return null;
		cell.setCellType(1);
		return cell.getStringCellValue();
	}

}
